package com.heima.user.service.Impl;

import com.heima.common.exception.CustException;
import com.heima.model.common.constants.user.UserRelationConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ApUserRelationServiceimpl implements ApUserRelationService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //1。检查参数
        //1.1查看用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);//1 需要登录后处理
        }
        //1.2判断operation的值0或1
        Short operation = dto.getOperation();
        if (operation.intValue() != 0 && operation.intValue() != 1) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "关注方式错误");
        }
        //1。3是否已经关注过
        /*   redisTemplate.boundZSetOps("");*/
        ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();
        //参数一：在集合中找key，  参数2：要找的元素   返回值：如果有这个元素返回score，如果没有返回null
        Double score = zSetOperations.score(UserRelationConstants.FOLLOW_LIST + user.getId(), String.valueOf(dto.getAuthorApUserId()));
        if (score == null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "你已经关注过该作者");
        }
        //1。4自己不能关注自己
        if (user.getId() == dto.getAuthorApUserId()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "自己不能关注自己");
        }

        //2。关注作者
        //如果operation是0 ZADD follow：1 时间2 zadd fans：2 时间1
        if (operation.intValue() == 0) {
            //key value object
            zSetOperations.add(UserRelationConstants.FOLLOW_LIST + user.getId(), String.valueOf(dto.getAuthorApUserId()), System.currentTimeMillis());
            zSetOperations.add(UserRelationConstants.FANS_LIST + dto.getAuthorApUserId(), String.valueOf(user.getId()), System.currentTimeMillis());

        } else {
            //3。取关作者
            //如果operation=1  ZREM follow：1 时间2 zrem fans：2 时间1
            zSetOperations.remove(UserRelationConstants.FOLLOW_LIST + user.getId(), String.valueOf(dto.getAuthorApUserId()));
            zSetOperations.remove(UserRelationConstants.FANS_LIST + dto.getAuthorApUserId(), String.valueOf(user.getId()));

        }
        return ResponseResult.okResult();
    }
}
